import { UploadComponentProps } from '@/components/Form/src/types'
import { useUserStoreWithOut } from '@/store/modules/user'
import { ElIcon, ElMessage } from 'element-plus'
import { UploadRawFile } from 'element-plus/lib/components'

const PATH_URL = import.meta.env.VITE_API_BASE_PATH
const MINIO_URL = import.meta.env.VITE_FILE_SERVER_PATH

// 基础上传配置
export const baseUploadImgProps = (
  avatarRef: { value: string },
  moduleName: string = 'default',
  beforeUpload?: (rawFile: UploadRawFile) => void,
  fileGrade: number = 0
): UploadComponentProps => ({
  action: PATH_URL + '/sysFile/upload.adw',
  showFileList: false,
  onSuccess: (_response, uploadFile) => {
    console.log('_response', _response)
    console.log('uploadFile', uploadFile)
    avatarRef.value = MINIO_URL + '/' + _response.data.storePath
  },
  beforeUpload: (rawFile) => {
    if (rawFile.type !== 'image/jpeg' && rawFile.type !== 'image/png') {
      ElMessage.error('头像图片必须为JPG/PNG格式!')
      return false
    } else if (rawFile.size / 1024 / 1024 > 2) {
      ElMessage.error('头像大小不能超过2MB!')
      return false
    }
    beforeUpload?.(rawFile)
    return true
  },
  data: {
    moduleName,
    fileGrade
  },
  headers: {
    Authorization: useUserStoreWithOut().getToken
  },
  slots: {
    default: () => (
      <>
        {avatarRef.value ? <img src={avatarRef.value} class="avatar" /> : null}
        {!avatarRef.value ? (
          <ElIcon class="avatar-uploader-icon" size="large">
            +
          </ElIcon>
        ) : null}
      </>
    )
  }
})
